import 'package:dailoz/dio/http_util.dart';
import 'package:dailoz/response_json_entity.dart';
import 'package:dailoz/utils/showAlertDialog.dart';
import 'package:dailoz/utils/toast.dart';
import 'package:dailoz/views/modify_page.dart';
import 'package:dailoz/widgets/task_widget.dart';
import 'package:flutter/material.dart';

class TaskService {
  static void editTask(BuildContext context, String taskId) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ModifyPage(
          taskId: taskId,
        ),
      ),
    );
  }

  static void deleteTask(BuildContext context, String taskId) {
    ShowDialog.showAlertDialog(context, "是否删除此任务？", () async {
      Navigator.pop(context);

      var response = await HttpUtil().delete("/task", {"taskId": taskId});
      ResponseJsonEntity responseJsonEntity =
          ResponseJsonEntity.fromJson(response);
      if (responseJsonEntity.code == 200) {
        showToast("${responseJsonEntity.message}, 请重新刷新");
      } else {
        showToast(responseJsonEntity.message);
      }
    });
  }

  static void cancelTask(BuildContext context, String taskId) {
    ShowDialog.showAlertDialog(context, "是否取消该任务？", () async {
      Navigator.pop(context);
      var response = await HttpUtil().put("/task/changeCancel", {"id": taskId});
      ResponseJsonEntity responseJsonEntity =
          ResponseJsonEntity.fromJson(response);

      // ignore: use_build_context_synchronously
      if (Navigator.canPop(context)) {
        // ignore: use_build_context_synchronously
        Navigator.pop(context);
      }
      showToast("${responseJsonEntity.message}, 请重新刷新");
    });
  }

  static void enableTask(BuildContext context, String taskId) {
    ShowDialog.showAlertDialog(context, "是否重启该任务？", () async {
      Navigator.pop(context);
      var response =
          await HttpUtil().put("/task/changePending", {"id": taskId});
      ResponseJsonEntity responseJsonEntity =
          ResponseJsonEntity.fromJson(response);
      // ignore: use_build_context_synchronously
      if (Navigator.canPop(context)) {
        // ignore: use_build_context_synchronously
        Navigator.pop(context);
      }
      showToast("${responseJsonEntity.message}, 请重新刷新");
    });
  }

  static void select(
      BuildContext context, String value, TaskWidget widget) async {
    switch (value) {
      case "edit":
        editTask(context, widget.taskId);
        break;
      case "delete":
        deleteTask(context, widget.taskId);
        break;
      case "disable":
        cancelTask(context, widget.taskId);
        break;
      case "enable":
        enableTask(context, widget.taskId);
        break;
    }
  }
}
